/**
 * 
 */
package cs340omega;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Set;

/**
 * @author byu.ryanpadilla
 *
 */
public class LocalID 
{
	
	private static int nextIDToAssign;
	private final int PORT = 3000;
	private final String HOST = "localhost";
	private int localID;
	
	public LocalID()
	{
		String addr;
		try 
		{
			addr = InetAddress.getLocalHost().toString();
		} 
		catch (UnknownHostException e) 
		{
			addr = HOST;
		}
		GlobalID id;
		ObjectDB database = new ObjectDB();
		Set<GlobalID> keys = database.getAllKeys();
		Iterator<GlobalID> iter = keys.iterator();

		int greatestID = 0;
		int tmp = 0;
		while (iter.hasNext())
		{
			id = iter.next();
			if((addr == id.getMachineHost() || addr == id.getMachineIP()) && id.getPort() == PORT)
			{
				tmp = id.getLocalID();
				if(tmp > greatestID)
				{
					greatestID = tmp;
				}
			}
		}
		nextIDToAssign = greatestID + 1;
		localID = nextIDToAssign;
		nextIDToAssign++;
	}
	public LocalID(String host, int p)
	{
		ObjectDB objDB = new ObjectDB();
		int highestID =  objDB.getHighestID(host, p);
		if(highestID != -1)
		{
			nextIDToAssign = highestID + 1;
		}
		localID = nextIDToAssign;
		//shouldn't ever really need this, but just in case -- to ensure all IDs assigned are unique;
		nextIDToAssign++;
	}
	
	public int getLocalID()
	{
		return localID;
	}

}
